import logging

import time
from datetime import datetime
from datetime import timedelta

from flask import g
from flask import redirect
from flask import render_template, current_app, jsonify
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, Category, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blue


@admin_blue.route('/news_type', methods=['GET', 'POST'])
@user_login_data
def news_type():
    if request.method == 'GET':
        # 查询分类
        try:
            categories = Category.query.all()
        except Exception as e:
            logging.error(e)
        categories_dicts = []
        for category in categories:
            categories_dicts.append(category.to_dict())

        data = {
            'categories': categories_dicts
        }

        return render_template('admin/news_type.html', data=data)

    # POST请求处理
    # 获取参数
    category_id = request.json.get('id')
    category_name = request.json.get('name')

    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 逻辑处理
    # 判断是否有分类id
    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
        if not category:
            return jsonify(errno=RET.NODATA, errmsg='无此分类')

        category.name = category_name
    else:
        # 如果没有分类id,就创建新模型
        category = Category()
        category.name = category_name
        db.session.add(category)
        # 提交
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库提交错误')

    # 返回结果
    return jsonify(errno=RET.OK, errmsg='保存成功')


@admin_blue.route('/news_edit_detail', methods=['GET', 'POST'])
@user_login_data
def news_edit_detail():
    if request.method == 'GET':
        # 获取参数
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_edit_detail.html', data={'errmsg': '无数据'})

        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)
            return render_template('admin/news_edit_detail.html', data={'errmsg': '无数据'})

        # 查询分类
        categorys = Category.query.all()
        c_list = []
        for category in categorys:
            c_dict = category.to_dict()
            c_dict['is_selected'] = False
            if category.id == news.category_id:
                c_dict['is_selected'] = True
            c_list.append(c_dict)

        data = {
            'news': news.to_dict(),
            'categories': c_list
        }

        return render_template('admin/news_edit_detail.html', data=data)

    # POST请求处理
    # 获取参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 校验参数
    if not all([news_id, title, digest, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 逻辑处理
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='无数据')

    if index_image:
        # 读取图片
        try:
            index_image = index_image.read()
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # 上传七牛云
        try:
            image_name = storage(index_image)
        except Exception as e:
            logging.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg='第三方上传错误')
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name

    # 更新相关修改数据
    news.category_id = category_id
    news.content = content
    news.title = title
    news.digest = digest

    # 提交
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库提交错误')

    # 返回结果
    return jsonify(errno=RET.OK, errmsg='编辑成功')


@admin_blue.route('/news_edit')
@user_login_data
def news_edit():
    page = request.args.get('p')
    keywords = request.args.get('keywords')
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1
    # 对所有已发布的新闻进行查询
    # 以时间降序排列，并分页显示
    # 关键字查询，对可选条件使用如下方法
    filters = [News.status == 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    news_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    data = {
        'news_list': news_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('admin/news_edit.html', data=data)


@admin_blue.route('/news_review_detail', methods=['GET', 'POST'])
@user_login_data
def news_review_detail():
    if request.method == 'GET':
        news_id = request.args.get('news_id')

        if not news_id:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})
        # 根据id查询出该新闻的信息
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            logging.error(e)

        if not news:
            return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

        data = {
            'news': news.to_dict()
        }

        return render_template('admin/news_review_detail.html', data=data)

    # POST请求的逻辑步骤
    # 获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 逻辑处理
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='没有该新闻')

    if action == 'accept':
        news.status = 0
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        news.reason = reason
        news.status = -1

    # 提交
    try:
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='数据库提交失败')

    # 返回数据
    return jsonify(errno=RET.OK, errmsg='审核成功')


# 新闻审核列表的显示
@admin_blue.route('/news_review')
@user_login_data
def news_review():
    # 获取参数
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords')
    try:
        page = int(page)
    except Exception as e:
        page = 1
        logging.error(e)

    # 根据条件对新闻进行查询并显示
    news_list = []
    current_page = 1
    total_page = 1
    # 添加关键字查寻功能
    filters = [News.status != 0]
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        logging.error(e)

    # 取出新闻并转字典
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {
        'news_list': news_dict_list,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('admin/news_review.html', data=context)


@admin_blue.route('/user_list')
@user_login_data
def user_list():
    # 获取参数
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as e:
        logging.error(e)
        page = 1

    # 分页查询
    users = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin == False) \
            .order_by(User.last_login.desc()) \
            .paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)

        users = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        logging.error(e)

    users_list = []
    for user in users:
        users_list.append(user.to_admin_dict())

    context = {
        'users': users_list,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/user_list.html', data=context)


@admin_blue.route('/user_count')
@user_login_data
def user_count():
    # 用户总数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        logging.error(e)

    # 每月新增人数
    now = time.localtime()
    mon_count = 0
    try:
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # 将字符串转化为时间格式
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        # 根据创建时间来查询当月新增人数
        mon_count = User.query.filter(User.is_admin == False,
                                      User.create_time >= mon_begin_date).count()
    except Exception as e:
        logging.error(e)

    # 每日新增人数
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        # 根据时间查询
        day_count = User.query.filter(User.is_admin == False,
                                      User.create_time > day_begin_date).count()
    except Exception as e:
        logging.error(e)

    # 图表显示
    # 找到现在时间的00:00:00
    now_date_str = datetime.now().strftime('%Y-%m-%d')
    now_date = datetime.strptime(now_date_str, '%Y-%m-%d')

    active_date = []
    active_count = []

    # 对时间向前推移一个月，使用for循环填充列表
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        # 添加时间进列表
        active_date.append(datetime.strftime(begin_date, '%Y-%m-%d'))
        # 使用最后登陆时间对每天活动的用户进行计数
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            logging.error(e)
        active_count.append(count)

        # 列表反转以适用与图表
    active_count.reverse()
    active_date.reverse()

    data = {
        'total_count': total_count,
        'mon_count': mon_count,
        'day_count': day_count,
        'active_count': active_count,
        'active_date': active_date
    }

    return render_template('admin/user_count.html', data=data)


@admin_blue.route('/index', methods=['GET', 'POST'])
@user_login_data
def index():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    return render_template('admin/index.html', data=data)


@admin_blue.route('/login', methods=['GET', 'POST'])
@user_login_data
def login():
    if request.method == 'GET':
        return render_template('admin/login.html')
    # POST请求下的逻辑
    # 获取数据
    username = request.form.get('username')
    password = request.form.get('password')
    # 校验数据
    if not all([username, password]):
        return render_template('admin/login.html', errmsg='请填写完全')

    # 查询该用户的信息
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        logging.error(e)
        return render_template('admin/login.html', errmsg='没有该用户存在')
        # 从数据库取值，要判断它是否为空
    if not user or not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')

    # 保存session数据
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    return redirect(url_for('admin.index'))
